
<template>
  <section>
    <!--工具条：关键字查询 + 新增-->
    <el-col :span="24" class="toolbar" >
      <el-form :inline="true">
        <el-form-item>
          <!--  v-perm="'role:add'" -->
          <el-button plain type="primary" @click="handleAdd">新增角色</el-button>
        </el-form-item>
      </el-form>
    </el-col>

    <!--列表:优秀实践，copy domain修改列表-->
    <el-table :data="roles" highlight-current-row v-loading="listLoading"
              @selection-change="selsChange" style="width: 100%;">
      <el-table-column type="selection" width="55">
      </el-table-column>
      <el-table-column type="index" width="60">
      </el-table-column>
      <el-table-column prop="name" label="角色名" width="180" :header-align="'center'" :align="'center'">
      </el-table-column>
      <el-table-column label="操作" width="230"  :align="'center'">
        <template scope="scope">
          <el-button v-perm="'role/editMenu'" type="danger" size="small" @click="EditMenu(scope.$index, scope.row)">菜单权限</el-button>
        </template>
      </el-table-column>
    </el-table>


    <!--工具条-->
    <el-col :span="24" class="toolbar">
      <el-pagination layout="total, sizes, prev, pager, next, jumper"
                     :page-sizes="[5, 10, 20, 50]"
                     @current-change="handleCurrentChange"
                     @size-change="handleSizeChange"
                     :current-page="currentPage" :page-size="pageSize"
                     :total="totals" style="float:left; margin-left: 40px;"  >
      </el-pagination>
    </el-col>

    <!--新增对话框-->
    <el-dialog title="新增角色" :visible.sync="AddFormVisible" :close-on-click-modal="false">
      <el-form :model="addForm" label-width="80px" :rules="addFormRules" ref="addForm">
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="addForm.name" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="角色编码" prop="sn">
          <el-input v-model="addForm.sn" auto-complete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="AddFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="submit" :loading="addLoading">保存</el-button>
      </div>
    </el-dialog>

<!--        分配菜单对话框-->
    <el-dialog title="修改数据" :visible.sync="saveFormVisibleMenu" :close-on-click-modal="false">
      <el-form :model="saveForm" label-width="80px" :hide-required-asterisk="true" :rules="saveFormRules" ref="saveForm">
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="saveForm.name" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="角色编码" prop="sn">
          <el-input v-model="saveForm.sn" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="菜单权限">
          <el-tree
              ref="tree"
              v-model="saveForm.selectedMenuData"
              :data="allMenuTree"
              :props="{ children: 'children', label: 'name',value:'id' }"
              node-key="id"
              accordion
              show-checkbox
              :default-expanded-keys="[]"
              :default-checked-keys="checkedKeys"
          ></el-tree>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="saveFormVisibleMenu = false">取消</el-button>
        <el-button type="primary" @click.native="saveSubmit" :loading="saveLoading">保存</el-button>
      </div>
    </el-dialog>
  </section>
</template>
<script>
import util from "../../common/js/util";

export default {
  data() {
    return {
      //分页显示所属数据
      roles: [],
      listLoading: false,
      currentPage: 1,
      pageSize: 5,
      totals: 0,

      form:{},
      //高级查询所需数据
      keyword: null,
      ids:[],
      menus:[],
      //多条数据选中
      sels: [],//列表选中列

      //添加或修改数据
      saveFormVisible: false,//添加或修改界面是否显示
      saveFormVisibleMenu:false,//编辑分配菜单是否显示
      saveLoading: false,
      saveFormRules: {
        name: [
          {required: true, message: '请输入名称', trigger: 'blur'}
        ],
        sn: [
          {required: true, message: '请输角色编码', trigger: 'blur'}
        ],
      },
      //编辑界面数据
      saveForm: {
        sn:'',
        name:'',
        selectedMenuId: [],
        selectedPressionId: [],
        selectedMenuData: [], // 这将存储所选的菜单数据
      },
      checkedKeys:[],
      allMenuTree: [], // 后端返回的全部菜单树数据
      expandedKeys: [], // 默认展开的节点

      checkedMenuKeys: [], // 已选中的菜单ID
      checkedPermissionKeys: [], // 已选中的权限ID
      permissionList: [],
      menuPath: {},
      menuExpand: false,
      menuNodeAll: false,
      roleMenus: [], // 角色拥有的菜单数据
      rolePermissions: [], // 角色拥有的权限数据
     //添加角色数据
      AddFormVisible:false,
      addForm:{
        name:'',
        sn:'',
      },
      addFormRules:{},
      addLoading:false,
    }
  },
  methods: {
    //获取角色列表
    getRoles() {
      let paras = {
        currentPage: this.currentPage,
        pageSize: this.pageSize,
        keyword: this.keyword
      };
      this.listLoading = true;
      this.$http.post("/role", paras).then(res => {
        this.totals = res.data.total;
        this.roles = res.data.records;
        this.listLoading = false;
      }).catch(res => {
        this.$message.error("获取分页数据失败!!!");
      })
    },
    //分页查询 - 点击某一页查询
    handleCurrentChange(val) {
      this.currentPage = val;
      this.getRoles();
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.currentPage = 1; // 重置当前页码为1
      this.getRoles();
    },
    //分配菜单
    EditMenu(index, row) {
      this.saveForm = Object.assign({}, row);
      //获取角色对应的菜单和权限
      const roleId = parseInt(row.id, 10);
      this.getMenuTree(roleId);
      this.saveFormVisibleMenu = true;
    },
    getMenuTree(roleId) {
      // 使用Vue.js提供的$http对象进行HTTP GET请求，包括角色id参数
      this.$http.get(`/menu/menuTree?roleId=${roleId}`).then(response => {
        // 获取后端返回的菜单树数据
        this.allMenuTree = response.data.resultObj.allMenuTree;

        const { menuIds, permissionIds } = response.data.resultObj.checkedKeys;
        console.log(menuIds)

// 根据 permissionIds 是否为空来确定默认展示的节点
        let defaultCheckedKeys;
        if (permissionIds && permissionIds.length > 0) {
          defaultCheckedKeys = permissionIds;
        } else {
          defaultCheckedKeys = menuIds;
        }

// 设置树组件的默认选中节点
        this.$refs.tree.setCheckedKeys(defaultCheckedKeys);
        // 直接将 checkedKeys 赋值给 default-checked-keys
      });
    },
    handleSelectedNodes(checkedNodes, callback) {
      // 初始化数组
      this.saveForm.selectedPressionId = [];
      this.saveForm.selectedMenuId = [];
      if (!Array.isArray(checkedNodes)) {
        checkedNodes = [checkedNodes];
      }
      // 处理选中的节点数据的逻辑，例如递归遍历、筛选等
      this.traverseAndFilterNodes(checkedNodes);
      // 执行回调函数
      callback();


        // this.saveForm.selectedMenuId = [];
        // this.saveForm.selectedPressionId = [];
        //
        // // 遍历所有选中的节点
        // checkedNodes.forEach(node => {
        //   // 如果节点是权限节点（第三级）
        //   if (node.menuType === 'F') {
        //     // 保存权限节点的 ID
        //     this.saveForm.selectedPressionId.push(Number(node.id));
        //
        //     // 获取该权限节点的父节点 ID（即二级菜单节点的 ID）
        //     const subMenuId = node.parentId;
        //
        //     // 检查该二级菜单节点是否已经被选中
        //     const isSubMenuSelected = this.saveForm.selectedMenuId.includes(subMenuId);
        //
        //     // 如果该二级菜单节点未被选中，将其添加到已选中的菜单列表中
        //     if (!isSubMenuSelected) {
        //       this.saveForm.selectedMenuId.push(Number(subMenuId));
        //     }
        //   }
        // });
        //
        // // 执行回调函数
        // callback();
      }
    ,
    // 递归遍历和保存数据的方法
    traverseAndFilterNodes(nodes) {
      // 递归遍历并筛选节点的逻辑
      nodes.forEach(node => {
        // 进行相应的处理，例如将数据存放到 saveForm 中
        // 注意：您需要根据实际需求修改这部分逻辑 node.menuType === 'M' ||
        if (node.menuType === 'C') {
            this.saveForm.selectedMenuId.push(Number(node.id));
        }
          if (node.menuType === 'F') {
          // 只保存用户选择的权限
            this.saveForm.selectedPressionId.push(Number(node.id));
            // 如果当前节点是权限（第三级），同时检查其对应的二级菜单节点是否已经被选择
            const parentId = node.parentId; // 假设节点有 parentId 属性表示父节点的 id

            const isParentMenuSelected = this.saveForm.selectedMenuId.includes(parentId);
            // 如果二级菜单未被选择，将其添加到选择列表中
            if (!isParentMenuSelected) {
              this.saveForm.selectedMenuId.push(Number(parentId));
            }
          }
        // 递归处理子节点
        if (node.children && node.children.length > 0) {
          this.traverseAndFilterNodes(node.children);
        }
      });
    },
    saveSubmit: function () {
      this.$refs.saveForm.validate((valid) => {
        if (valid) {
          this.$confirm('确认修改角色的菜单权限数据信息吗？', '提示', {}).then(() => {
            // 获取异步请求的选中节点数据
            const checkedNodes = this.$refs.tree.getCheckedNodes();
            console.log(checkedNodes)
            // 处理选中的节点数据
            this.handleSelectedNodes(checkedNodes, () => {
              let para = Object.assign({}, this.saveForm);
              this.$http.put("/role/updatemenu", para).then((res) => {
                if (res.data.success) {
                  this.$message({
                    message: '角色数据修改成功',
                    type: 'success'
                  });
                  this.$refs['saveForm'].resetFields();// 重置表单
                  this.getRoles(); // 重新加载
                } else {
                  this.$message.error("操作失败【500】");
                }
                this.saveFormVisibleMenu = false;
                this.saveLoading = false;
              }).catch(res => {
                this.$message.error("系统错误【400,404】");
              });
            });
          });
        }
      });
    },
    //点击添加按钮弹出对话框
    handleAdd: function () {
      //显示对话框
      this.AddFormVisible = true;
    },
    submit:function (){
      this.$refs.addForm.validate((valid) => {
        if (valid) {
            this.$confirm('确认新增角色信息吗？', '提示', {}).then(() => {
              this.addLoading = true;
              let para = Object.assign({}, this.addForm);
              this.$http.put("/role", para).then(res => {
                if (res.data.success) {
                  this.$message({
                    message: '角色新增成功',
                    type: 'success'
                  });
                  this.$refs['addForm'].resetFields();
                } else {
                  this.$message.error("系统繁忙，请稍后重试!!!【500】");
                }
                this.addLoading = false;
                this.AddFormVisible = false;
                this.getRoles();
              });
            });
          }
        });
      },
    selsChange: function (sels) {
      this.sels = sels;
    },
  },
  mounted() {
    this.getRoles();
  }
}

</script>

<style scoped>

</style>
